using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Text.RegularExpressions;
using Blog.Importer.WebImporter;

namespace Blog.Importer
{
  public class BlogWriter
  {
    public static BlogImporter GetService(string path, string login, string password)
    {
      BlogImporter service = new WebImporter.BlogImporter();
      string url = path;

      url += "api/blogimporter.asmx"; // TODO: Pull from RSD for 1.2

      service.Url = url;
      service.AuthHeaderValue = new AuthHeader();
      service.AuthHeaderValue.Username = login;
      service.AuthHeaderValue.Password = password;
      return service;
    }

    public static string FilterContent(string content, BlogImporter service, string blogPath, string fileOption, string fileLocation)
    {
      //File Options:
      //--Download Blog Files and Images
      //--Blog Files & Images Moved Manually
      //--Ignore Blog Files & Images
      string newContent = content;
      if (fileOption != "Ignore Blog Files & Images")
      {
        // Get Blog Handler paths
        string fileHandler = service.BlogFileHandler();
        string imageHandler = service.BlogImageHandler();

        // Check Full Path first
        int placeHolder = newContent.IndexOf('"' + fileLocation);
        while (placeHolder >= 0)
        {
          // Change Path
          string oldPath = newContent.Substring(placeHolder + 1, newContent.IndexOf('"', placeHolder + 1) - placeHolder - 1);
          string shortPath = oldPath.Substring(fileLocation.Length);
          newContent = newContent.Remove(placeHolder + 1, oldPath.Length);

          if (oldPath.ToLower().Contains(".jpg") || oldPath.ToLower().Contains(".gif") || oldPath.ToLower().Contains(".png"))
            newContent = newContent.Insert(placeHolder + 1, blogPath + imageHandler + shortPath);
          else
            newContent = newContent.Insert(placeHolder + 1, blogPath + fileHandler + shortPath);
          

          // Download?
          if (fileOption == "Download Blog Files and Images")
            service.GetFile(oldPath, shortPath);

          // Get Next
          placeHolder = newContent.IndexOf('"' + fileLocation, placeHolder + 1);
        }

        //TODO: Check for Relative Path

      }

      return newContent;
    }

    public static bool ValidateDestination(string path, string login, string password)
    {
      bool response;
      try
      {
        BlogImporter service = GetService(path, login, password);
        string test = service.BlogVersion();
        response = true;
      }
      catch
      {
        response = false;
      }

      return response;
    }

  }


}
